package com.link.play.fit.ai.ui.guide

import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.link.play.fit.ai.R
import com.link.play.fit.ai.databinding.FgWeightEasyBinding
import com.link.play.fit.ai.ui.guide.ac.GuidePbAc
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch


class WeightEasyFg : BasePageFragment<FgWeightEasyBinding>(FgWeightEasyBinding::inflate) {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val userGuideState = (requireActivity() as GuidePbAc).viewModel.userGuideState
        lifecycleScope.launch {
            userGuideState.collectLatest {
                when (it.goal) {
                    0 -> {
                        val colorString =
                            if (it.imperialMetric) "${it.goalWeightKg - it.weightKg} kg" else "${it.goalWeightLbs - it.weightLbs} lbs"
                        val sb = SpannableString(getString(R.string.easy_hint, getString(R.string.gaining), colorString))

                        val startIndex = sb.indexOf(colorString)
                        val endIndex = startIndex + colorString.length

                        sb.setSpan(
                            ForegroundColorSpan(ContextCompat.getColor(requireContext(), R.color.colorPrimary)),
                            startIndex,
                            endIndex,
                            Spannable.SPAN_INCLUSIVE_INCLUSIVE
                        )

                        binding.tv.text = sb
                    }

                    2 -> {
                        val colorString =
                            if (it.imperialMetric) "${it.weightKg - it.goalWeightKg} kg" else "${it.weightLbs - it.goalWeightLbs} lbs"
                        val sb = SpannableString(getString(R.string.easy_hint, getString(R.string.losing), colorString))

                        val startIndex = sb.indexOf(colorString)
                        val endIndex = startIndex + colorString.length

                        sb.setSpan(
                            ForegroundColorSpan(ContextCompat.getColor(requireContext(), R.color.colorPrimary)),
                            startIndex,
                            endIndex,
                            Spannable.SPAN_INCLUSIVE_INCLUSIVE
                        )

                        binding.tv.text = sb
                    }

                }
            }
        }
    }
}